package com.easy.demo;


import org.activiti.engine.impl.util.json.JSONObject;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public ModelAndView errorHandler(HttpServletRequest request, NoHandlerFoundException exception, HttpServletResponse response) {
        return commonHandler(request, response,
                exception.getClass().getSimpleName(),
                HttpStatus.FORBIDDEN.value(),
                exception.getMessage());
    }


    /**
     * 500异常处理
     */
    @ExceptionHandler(value = Exception.class)
    public ModelAndView errorHandler(HttpServletRequest request, Exception exception, HttpServletResponse response) {
        return commonHandler(request, response,
                exception.getClass().getSimpleName(),
                HttpStatus.INTERNAL_SERVER_ERROR.value(),
                exception.getMessage());
    }


    //Assert异常
    @ExceptionHandler(IllegalArgumentException.class)
    public ModelAndView errorHandler(HttpServletRequest request, IllegalArgumentException exception, HttpServletResponse response) {
        return commonHandler(request, response,
                exception.getClass().getSimpleName(),
                HttpStatus.INTERNAL_SERVER_ERROR.value(),
                exception.getMessage());
    }


    /**
     * 异常处理数据处理
     */
    private ModelAndView commonHandler(HttpServletRequest request, HttpServletResponse response,
                                       String error, int httpCode, String message) {
        return determineOutput(request, response, error,  httpCode,  message);
    }

    /**
     * 异常输出处理
     */
    private ModelAndView determineOutput(HttpServletRequest request, HttpServletResponse response, String error, int httpCode, String message) {
        if (!(
                request.getHeader("accept").contains("application/json")
                        || (request.getHeader("X-Requested-With") != null && request.getHeader("X-Requested-With").contains("XMLHttpRequest"))
        )) {
            //页面返回
            ModelAndView modelAndView = new ModelAndView("error");
            modelAndView.addObject("error", error);
            modelAndView.addObject("httpCode", httpCode);
            modelAndView.addObject("message", message);
            return modelAndView;
        } else {
            response.setCharacterEncoding("UTF8");
            response.setHeader("Content-Type", "application/json");
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("error", error);
                jsonObject.put("httpCode", httpCode);
                jsonObject.put("status", httpCode);
                jsonObject.put("code", httpCode);
                jsonObject.put("msg", message);
                response.getWriter().write(jsonObject.toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    }


}
